<template>
  <div class="app-container">
    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="收入来源:">
        <!-- <el-select v-model="incomeListForm.source" clearable placeholder="请选择"> -->
        <el-select v-model="incomeSource" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in codeList"
            :key="item.encoding"
            :label="item.name"
            :value="item.encoding"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item class="switch">
        <el-switch
          style="display: block;"
          v-model="dataQueryFalg"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="时间范围："
          inactive-text="时间节点"
          @change = "()=>{
            if(dataQueryFalg){
              incomeListForm.dateStr = []
              year = ''
              month = ''
              dates = []
            }
            else 
              incomeListForm.dates = []
          }"
        >
        </el-switch>
      </el-form-item>
      <el-form-item v-if="dataQueryFalg">
        <el-date-picker
          v-model="incomeListForm.dates"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item v-if="!dataQueryFalg">
        <div class="block">
          <span class="demonstration">年</span>
          <el-date-picker v-model="year" type="year" placeholder="选择年" value-format="yyyy" @change = "clearOtherDate('year')">
          </el-date-picker>
          <span class="demonstration">月</span>
          <el-date-picker v-model="month" type="month" placeholder="选择月" value-format="yyyyMM" @change = "clearOtherDate('month')">
          </el-date-picker>
          <span class="demonstration">多个日期</span>
          <el-date-picker
            type="dates"
            v-model="dates"
            placeholder="选择一个或多个日期"
            value-format="yyyyMMdd"
            @change = "clearOtherDate('dates')"
          >
          </el-date-picker>
        </div>
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" @click="searchData()"
        v-if="hasPerm('income.list')">查询</el-button
      >
      <el-button
        type="default"
        @click="
          () => {
            year = '';
            month = '';
            dates = [];
            incomeSource = '';
            incomeListForm.dates = [];
            incomeListForm.dateStr = [];
          }
        "
        >清空</el-button
      >
    </el-form>

    <el-button
      type="success"
      size="small"
      style="margin-bottom: 10px"
      icon="el-icon-document-add"
      @click="create()"
      v-if="hasPerm('income.add')">新增</el-button
    >

    <span>总计：{{moneySum}}</span>

    <el-table
      :data="list"
      element-loading-text="数据加载中"
      border
      fit
      stripe
      highlight-current-row
      :key="tableKey"
    >
      <el-table-column label="序号" width="70" align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column label="收入来源" width="160" align="center">
        <template slot-scope="scope">
          {{ codeMap[scope.row.source] }}
        </template>
      </el-table-column>
      <el-table-column
        prop="money"
        label="收入金额"
        width="100"
        align="center"
      />
      <el-table-column prop="detail" label="收入明细" align="center" />
      <el-table-column
        prop="incomeDate"
        label="收入日期"
        width="180"
        align="center"
      />

      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click="update(scope.row)"
            v-if="hasPerm('income.update')">修改</el-button
          >
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            @click="removeById(scope.row.id)"
            v-if="hasPerm('income.delete')">删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 拟态框 -->
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="dialogFormValue"
      :close="
        () => {
          this.$nextTick.incomeListForm.clearValidate();
        }
      "
    >
      <el-form
        ref="incomeListForm"
        :model="incomeListForm"
        :rules="menuValidateRules"
        label-width="120px"
      >
        <el-form-item label="收入来源" prop="source">
          <!-- <el-input v-model="incomeListForm.source" /> -->
          <!-- <template slot-scope="scope"> -->
          <el-select
            v-model="incomeListForm.source"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in codeList"
              :key="item.encoding"
              :label="item.name"
              :value="item.encoding"
            >
            </el-option>
          </el-select>
          <!-- </template> -->
        </el-form-item>
        <el-form-item label="收入金额" prop="money">
          <el-input v-model="incomeListForm.money" />
        </el-form-item>
        <el-form-item label="收入明细" prop="detail">
          <el-input v-model="incomeListForm.detail" />
        </el-form-item>
        <el-form-item label="收入日期" prop="incomeDate">
          <el-date-picker
            v-model="incomeListForm.incomeDate"
            type="datetime"
            placeholder="选择收入日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item class="switch" label="是否计入">
          <el-switch
          style="display: block;"
          v-model="incomeListForm.isIncluded"
          active-color="#ff4949"
          inactive-color="#13ce66"
          active-text="不计入收入"
          inactive-text="计入收入"
          :active-value="false"
          :inactive-value="true"
        >
        </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="restData()">取 消</el-button>
        <el-button type="primary" @click="append()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      style="padding: 30px 0; text-align: center"
      layout="total, prev, pager, next, jumper"
      @current-change="initTableList"
    />
  </div>
</template>
<script>
import incomeList from "@/api/account/incomeList";
import codeLibraryList from "@/api/account/codeLibraryList";
import { getToken } from "@/utils/auth";
import { getInfo } from "@/api/login";

const incomeForm = {
  userId: "",
  source: "",
  money: "",
  detail: "",
  isIncluded: true,
  incomeDate: "",
};

export default {
  data() {
    //定义变量和初始值
    return {
      list: null, //查询之后接口返回集合
      page: 1, //当前页
      limit: 10, //每页记录数
      total: 0, //总记录数
      dialogFormVisible: false,
      incomeListForm: { ...incomeForm },
      userId: "",
      codeMap: {}, //用于list的码值转换
      codeList: {}, //用于info的选择器
      dataQueryFalg: true,
      incomeSource: "", //收入来源，查询用
      moneySum: 0,
      year: "",
      month: "",
      dates: [],
      tableKey: 0,
      menuValidateRules: {
        //这里还有blur触发方法； 如果设为none，那么只有this.$refs[formName]['validate']时才会验证
        source: [
          { required: true, trigger: "change", message: "请选择收入来源" },
        ],
        money: [
          { required: true, trigger: "blur", message: "金额必须输入" },
          {
            validator: (rule, value, callback) => {
              if (
                /(^[1-9]([0-9]{0,5})(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(
                  value
                ) == false
              ) {
                callback(new Error("请输入正确的金额"));
              } else {
                callback();
              }
            },
          },
        ],
        incomeDate: [
          { required: true, trigger: "change", message: "收入日期必须输入" },
        ],
      },
      dialogFormValue: "新增",
    };
  },
  created() {
    //在页面渲染之前执行，一般调用methods定义的方法
    codeLibraryList.findAllByCode("sourceRevenue").then((res) => {
      this.codeList = res.data.rows;
      this.codeList.forEach((item) => {
        this.codeMap[item.encoding] = item.name;
      });
    });
    getInfo(getToken()).then((res) => {
      this.userId = res.data.userId;
      this.initTableList();
    });
  },
  methods: {
    //码值列表的方法
    initTableList(page = 1) {
      console.log("被调用",this.incomeListForm);
      this.page = page;
      this.incomeListForm.userId = this.userId;
      this.incomeListForm.source = this.incomeSource;
      incomeList
        .getIncomeListPage(this.page, this.limit, this.incomeListForm)
        .then((response) => {
          //response接口返回的数据
          this.list = response.data.rows;
          this.total = response.data.total;
          this.tableKey = Math.random();
          console.log(response.data.rows);
        }) //请求成功
        .catch((error) => {
          console.log(error);
        }); //请求失败
      incomeList.getMoneySum(this.incomeListForm).then((res)=>{
        this.moneySum = res.data.moneySum;
      })
    },
    create() {
      this.dialogFormVisible = true;
      this.incomeListForm = { ...incomeForm };
      //等弹窗里的form表单的dom渲染完在执行this.$refs.incomeListForm.clearValidate()，去除验证
      this.$nextTick(() => {
        if (this.$refs.incomeListForm) {
          this.$refs.incomeListForm.clearValidate();
        }
      });
    },
    restData() {
      this.dialogFormVisible = false;
      this.incomeListForm = { ...incomeForm };
    },

    append() {
      this.incomeListForm.userId = this.userId;
      this.$refs.incomeListForm.validate((valid) => {
        if (valid) {
          if (!this.incomeListForm.gmtCreate) {
            console.log("添加数据成功");
            incomeList.saveIncome(this.incomeListForm).then((res) => {
              this.$message({
                type: "success",
                message: "添加数据成功!",
              });
              this.restData();
              this.initTableList();
            });
          } else {
            incomeList.updateById(this.incomeListForm).then((res) => {
              this.$message({
                type: "success",
                message: "更新数据成功!",
              });
              this.restData();
              this.initTableList();
            });
            console.log("更新数据成功");
          }
        }
      });
    },
    removeById(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          incomeList.removeById(id).then((res) => {
            this.$message({
              type: "success",
              message: "删除数据成功!",
            });
            this.restData();
            this.initTableList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    update(row) {
      //等弹窗里的form表单的dom渲染完在执行this.$refs.incomeListForm.clearValidate()，去除验证
      this.$nextTick(() => {
        if (this.$refs.incomeListForm) {
          this.$refs.incomeListForm.clearValidate();
        }
      });
      console.log('row',row)
      this.dialogFormVisible = true;
      this.incomeListForm = { ...row };
    },
    searchData() {
      this.initTableList();
    },
    clearOtherDate(arg){
      if(arg === 'year') {
        this.month = '';
        this.dates = [];
        console.log('year',this.year)
        this.incomeListForm.dateStr = [];
        this.incomeListForm.dateStr.push(this.year);
      } else if(arg === 'month') {
        this.year = '';
        this.dates = [];
        console.log('month',this.month)
        this.incomeListForm.dateStr = [];
        this.incomeListForm.dateStr.push(this.month);
      } else if(arg === 'dates') {
        this.month = '';
        this.year = '';
        console.log('dates',this.dates)
        this.incomeListForm.dateStr = [];
        this.incomeListForm.dateStr = this.dates;
      }
    }
  },
};
</script>
<style scoped>
.el-form-item.switch /deep/ .el-form-item__content {
  height: 40px;
  line-height: 40px;
  display: flex;
  align-items: center;
}
</style>
<style>
.el-switch__label--right {
  font-weight: 700;
}
.el-switch__label--left {
  font-weight: 700;
}
</style>